package com.cet.qz.unit01.chapter1_3;

import java.util.Iterator;

/**
 * @program: algorithm
 * @description: 数组实现
 * @author: 陈恩涛
 * @create: 2021-04-23 14:40
 **/
public class GeneralizedQueue<Item> implements Iterable<Item> {

    private Item[] a = (Item[]) new Object[1];
    private int first,last, n;

    public boolean isEmpty() {
        return n == 0;
    }

    private void resize(int max) {
        Item[] items = (Item[]) new Object[max];
        int j = 0;
        for (int i = first; i < last; i++) {
            items[j++] = a[i];
        }
        first = 0;
        last = n;
        a = items;
    }

    public void insert(Item item) {
        if (last == a.length) {
            if (n < a.length) {
                resize(a.length);
            } else {
                resize(2 * a.length);
            }
        }
        a[last++] = item;
        n++;
    }

    public Item delete(int k) {
        if (k > n || k <= 0) {
            throw new RuntimeException("index is out the bounds");
        }
        int target = first + k - 1;
        Item result = a[target];
        for (int i = target; i > first; i--) {
            a[i] = a[i - 1];
        }
        a[first++] = null;
        n--;
        return result;
    }

    @Override
    public Iterator<Item> iterator() {
        return new QueueIterator(first, last);
    }

    class QueueIterator implements Iterator<Item> {

        private int head;
        private int tail;

        public QueueIterator(int head, int tail) {
            this.head = head;
            this.tail = tail;
        }

        @Override
        public boolean hasNext() {
            return head != tail;
        }

        @Override
        public Item next() {
            return a[head++];
        }

        @Override
        public void remove() {

        }
    }

    public static void main(String[] args) {
        GeneralizedQueue<Integer> generalizedQueue = new GeneralizedQueue<>();
        generalizedQueue.insert(1);
        generalizedQueue.insert(2);
        generalizedQueue.insert(3);
        for (Integer i : generalizedQueue) {
            System.out.println(i);
        }
        System.out.println("===========================");
        System.out.println(generalizedQueue.delete(2));
    }

}
